package cn.funnymap.lgis.mp.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JSONArray数据类型处理器
 *
 * @author jiao xn
 */
@ConditionalOnClass(BaseTypeHandler.class)
@MappedTypes({JSONArray.class})
public class JsonbWithJsonArrayTypeHandler extends BaseTypeHandler<JSONArray> {
    private static final PGobject JSON_OBJECT = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONArray o, JdbcType jdbcType) throws SQLException {
        if (preparedStatement != null) {
            JSON_OBJECT.setType("jsonb");
            JSON_OBJECT.setValue(JSON.toJSONString(o));
            preparedStatement.setObject(i, JSON_OBJECT);
        }
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JSONArray.parse(resultSet.getString(s));
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return JSONArray.parse(resultSet.getString(i));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return JSONArray.parse(callableStatement.getString(i));
    }
}
